import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { setupRouterGuards } from './guards'
import HomeView from '../views/HomeView.vue'
import Dashboard from '../views/Dashboard.vue'
import LoginView from '../views/LoginView.vue'
import { microApps } from '../microApps.config'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      title: '登录',
      layout: 'empty'
    }
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: {
      title: '首页',
      icon: 'home',
      keepAlive: true
    }
  },
  {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
    meta: {
      title: '仪表板',
      icon: 'dashboard',
      keepAlive: true,
      requiredRoles: ['ADMIN', 'USER', 'TEACHER']
    }
  },
  {
    path: '/profile',
    name: 'profile',
    component: () => import('../views/ProfileView.vue'),
    meta: {
      title: '个人信息',
      icon: 'user',
      keepAlive: false
    }
  },
  {
    path: '/about',
    name: 'about',
    // 路由级代码分割，生成单独的chunk (about.[hash].js)
    // 访问路由时懒加载
    component: () => import('../views/AboutView.vue'),
    meta: {
      title: '关于',
      icon: 'info',
      keepAlive: false
    }
  },
  {
    path: '/test-micro',
    name: 'test-micro',
    component: () => import('../views/TestMicroApp.vue'),
    meta: {
      title: '微应用测试',
      icon: 'test',
      keepAlive: false,
      requiredRoles: ['ADMIN']
    }
  },
  ...microApps.map(app => ({
    path: `${app.activeRule}/:catchAll(.*)*`,
    name: app.name,
    component: () => import('../views/MicroAppView.vue'),
    meta: {
      title: app.title,
      icon: app.icon,
      keepAlive: true,
      isMicroApp: true,
      microAppName: app.name,
      requiredRoles: app.requiredRoles || [], // 确保为空数组而不是undefined
      permission: app.permission
    }
  })),
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('../views/404.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 设置路由守卫
setupRouterGuards(router)

export default router 